package com.aitesting.controller;


import com.aitesting.common.CommonResult;
import com.aitesting.model.Project;
import com.aitesting.service.ProjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 项目管理
 * @author zz
 * @since 2022-02-20
 */
@Slf4j
@RestController
@RequestMapping("/project")
public class ProjectController {

    @Autowired
    private ProjectService projectService;

    /**
     * 根据id查询项目信息
     * @param id 项目id
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public CommonResult<Project> getById(@PathVariable("id") Integer id) {
        return CommonResult.success(projectService.getById(id));
    }

    /**
     * 查询所有项目信息
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/listAll", method = RequestMethod.GET)
    public CommonResult<Project> getList() {
        return CommonResult.success(projectService.list());
    }

    /**
     * 新增项目
     * @param project 项目对象
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public CommonResult<Project> create(@Validated @RequestBody Project project, BindingResult result){
        boolean isOk = projectService.save(project);
        if (isOk) {
            return CommonResult.success(project);
        }else {
            log.error("新增项目失败,数据不合法 {}", project);
            return CommonResult.failed();
        }
    }

    /**
     * 根据id删除项目
     * @param id 项目id
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public CommonResult<Project> delete(@PathVariable Integer id) {
        boolean isOk = projectService.removeById(id);
        if (isOk) {
            return CommonResult.success(null);
        }else {
            return CommonResult.failed();
        }
    }

    /**
     * 根据id更新项目信息
     * @param project 项目对象
     * @return CommonResult(code,message,data)
     */
    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public CommonResult<Project> update(@RequestBody Project project) {
        boolean isOk = projectService.updateById(project);
        if (isOk) {
            return CommonResult.success(project);
        }else {
            log.error("更新项目失败,数据不合法 {}", project);
            return CommonResult.failed();
        }
    }
}

